package com.sg.business.model.bpmservice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.bson.types.ObjectId;

import com.mobnut.db.model.IContext;
import com.mobnut.db.model.ModelService;
import com.mobnut.db.model.PrimaryObject;
import com.mongodb.DBObject;
import com.sg.bpm.service.task.ServiceProvider;
import com.sg.bpm.workflow.utils.WorkflowUtils;
import com.sg.business.model.Document;
import com.sg.business.model.Work;

public class DocumentPhaseService extends ServiceProvider {

	public DocumentPhaseService() {
	}

	@Override
	public Map<String, Object> run(Object parameter) {
		Map<String, Object> result = new HashMap<String, Object>();
		Object content = getInputValue("content");
		Object products = getInputValue("products");
		Object type = getInputValue("type");
		if (content instanceof String) {
			String jsonContent = (String) content;
			PrimaryObject host = WorkflowUtils.getHostFromJSON(jsonContent);
			if (host instanceof Work) {
				DBObject processData = WorkflowUtils
						.getProcessInfoFromJSON(jsonContent);
				String processId = (String) processData.get("processId");
				String processName = (String) processData.get("processName");
				IContext context = new BPMServiceContext(processName, processId);
				try {
					if (products != null) {
						String[] split = ((String) products).split(",");
						for (String product : split) {
							Document document = ModelService.createModelObject(
									Document.class, new ObjectId(product));
							doModifyPhase(context, document);
							if ("30".equals(type)) {
								doModifyPhasePart(context, document);
							}
						}
					}
				} catch (Exception e) {
					result.put("returnCode", "ERROR");
					result.put("returnMessage", e.getMessage());
				}
			}
		}
		return result;
	}

	private void doModifyPhasePart(IContext context, Document document)
			throws Exception {
		List<Document> relativeList = document
				.getDownPartRelativeObjectList(false);
		for (Document doc : relativeList) {
			doModifyPhase(context, doc);
			doModifyPhasePart(context, doc);
		}
	}

	private void doModifyPhase(IContext context, Document document)
			throws Exception {
		document.doModifyPhase(context, "D");
		List<Document> relativeList = document.getCADRelativeObjectList(false);
		for (Document relativeDoc : relativeList) {
			relativeDoc.doModifyPhase(context, "D");
		}
		relativeList = document.getDocumentRelativeObjectList(false);
		for (Document relativeDoc : relativeList) {
			relativeDoc.doModifyPhase(context, "D");
		}
	}

}
